package cn.fetosoft.woodpecker.core.pubsub.zookeeper;

import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * @author guobingbing
 * @wechat t_gbinb
 * @since 2021/9/12 20:58
 */
abstract class AbstractZookeeper {

    public static final String CHARSET = "utf-8";
    @Resource
    protected CuratorFramework client;

    /**
     * 创建节点
     * @param path
     * @param mode
     * @param data
     * @throws Exception
     */
    protected void createNode(String path, CreateMode mode, String data) throws Exception{
        Stat stat = client.checkExists().forPath(path);
        if(stat!=null) {
            client.delete().deletingChildrenIfNeeded().forPath(path);
        }
        client.create().creatingParentsIfNeeded().withMode(mode).forPath(path);
        if(StringUtils.isNotBlank(data)) {
            client.setData().forPath(path, data.getBytes(CHARSET));
        }
    }

    /**
     * 节点不存在则创建
     * @param path
     * @param mode
     * @throws Exception
     */
    protected void createNotExist(String path, CreateMode mode) throws Exception{
        Stat stat = client.checkExists().forPath(path);
        if(stat==null) {
            client.create().creatingParentsIfNeeded().withMode(mode).forPath(path);
        }
    }

    @PreDestroy
    public void destroy(){
        if(client!=null){
            client.close();
        }
    }
}
